﻿using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class Drag3D : MonoBehaviour
{
    public Action onStartDrag, onDraging, onFinishDrag;

    Vector3 offset;
    float y;
    bool canDrag;

    protected virtual void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit) && hit.collider.gameObject == gameObject && transform.parent.name == "LangJia")
            {
                y = transform.position.y;
                offset = transform.position - GetRayIntersectionWithHeight(ray, y);
                canDrag = true;
                onStartDrag?.Invoke();
            }
        }
        if (canDrag && Input.GetMouseButtonUp(0))
        {
            canDrag = false;
            onFinishDrag?.Invoke();
        }
        if (canDrag)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Vector3 targetPos = GetRayIntersectionWithHeight(ray, y) + offset;
            Vector3 pos = transform.position;
            pos.x = targetPos.x;
            pos.z = targetPos.z;
            transform.position = pos;
            onDraging?.Invoke();
        }
    }

    //获取射线与指定高度的水平面的相交点
    private Vector3 GetRayIntersectionWithHeight(Ray ray, float y)
    {
        if (ray.direction.y == 0)
        {
            return Vector3.zero;
        }
        float t = (y - ray.origin.y) / ray.direction.y;
        if (t < 0)
        {
            return Vector3.zero;
        }
        Vector3 intersectionPoint = ray.origin + t * ray.direction;
        return intersectionPoint;
    }
}